package zzjson.rabbitmq.message;

import com.rabbitmq.client.*;
import zzjson.rabbitmq.BaseRabbitMq;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2019 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : com.zzjson.rabbitmq.message</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2019年04月25日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class MessageConsumer {
	private final static String QUEUE_NAME = "ORIGIN_QUEUE";

	public static void main(String[] args) throws Exception {
		Connection conn = BaseRabbitMq.getConn();
		// 创建消息通道
		Channel channel = conn.createChannel();

		// 声明队列（默认交换机AMQP default，Direct）
		// String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);

		System.out.println(" Waiting for message....");

		// 创建消费者
		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
									   byte[] body) throws IOException {
				String msg = new String(body, StandardCharsets.UTF_8);
				System.out.println("Received message : '" + msg + "' ");
				System.out.println("messageId : " + properties.getMessageId());
				System.out.println(properties.getHeaders().get("name") + " -- " + properties.getHeaders().get("level"));
			}
		};

		// 开始获取消息
		// String queue, boolean autoAck, Consumer callback
		channel.basicConsume(QUEUE_NAME, true, consumer);

		BaseRabbitMq.close(channel, conn);

	}
}